package com.xidian.zhiancloud.service.emergencyManagement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.emergencyManagement.EmergencyPlanManagementDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.emergencyManagement.EmergencyPlanManagementQO;
import com.xidian.zhiancloud.vo.emergencyManagement.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmergencyPlanManagementService extends ServiceImpl<EmergencyPlanManagementMapper, EmergencyPlanManagement> implements IService<EmergencyPlanManagement> {

    @Autowired
    private EmergencyPlanManagementMapper emergencyPlanManagementMapper;

    @Autowired
    private ResponsibilitiesAndTasksMapper responsibilitiesAndTasksMapper;

    @Autowired
    private RevisionRecordMapper revisionRecordMapper;

    @Autowired
    private ReviewRecordMapper reviewRecordMapper;

    @Autowired
    private EmergencyMaterialsInventoryManagementMapper emergencyMaterialsInventoryManagementMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPositionMapper sysPositionMapper;

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean add(EmergencyPlanManagementDTO emergencyPlanManagementDTO) {
        EmergencyPlanManagement emergencyPlanManagement = emergencyPlanManagementDTO.getEmergencyPlanManagement();
        int result = emergencyPlanManagementMapper.insert(emergencyPlanManagement);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        int count= 0;
        for(int i=0;i<emergencyPlanManagementDTO.getResponsibilitiesAndTasksList().size();i++){
            emergencyPlanManagementDTO.getResponsibilitiesAndTasksList().get(i).setEmergencyPlanId(emergencyPlanManagementDTO.getEmergencyPlanManagement().getId());
            responsibilitiesAndTasksMapper.insert(emergencyPlanManagementDTO.getResponsibilitiesAndTasksList().get(i));
            count++;
        }
        if (count != emergencyPlanManagementDTO.getResponsibilitiesAndTasksList().size()) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
//        for (ResponsibilitiesAndTasks responsibilitiesAndTasks : emergencyPlanManagementDTO.getResponsibilitiesAndTasksList()) {
//            responsibilitiesAndTasks.setEmergencyPlanId(emergencyPlanManagementDTO.getEmergencyPlanManagement().getId());
//            int tmp1 = responsibilitiesAndTasksMapper.insert(responsibilitiesAndTasks);
//            if (tmp1 == 0) {
//                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
//            }
//        }
//
//        for (RevisionRecord revisionRecord : emergencyPlanManagementDTO.getRevisionRecordList()) {
//            revisionRecord.setEmergencyPlanId(emergencyPlanManagementDTO.getEmergencyPlanManagement().getId());
//            int tmp2 = revisionRecordMapper.insert(revisionRecord);
//            if (tmp2 == 0) {
//                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
//            }
//        }
//
//        for (ReviewRecord reviewRecord : emergencyPlanManagementDTO.getReviewRecordList()) {
//            reviewRecord.setEmergencyPlanId(emergencyPlanManagementDTO.getEmergencyPlanManagement().getId());
//            int tmp3 = reviewRecordMapper.insert(reviewRecord);
//            if (tmp3 == 0) {
//                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
//            }
//        }
        return true;
    }

    public EmergencyPlanManagementDTOVO getDTOVOById(Long id) {
        EmergencyPlanManagement emergencyPlanManagement = emergencyPlanManagementMapper.selectById(id);
        if (emergencyPlanManagement == null) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        //修改为mybatis plus的条件查询
        QueryWrapper<ResponsibilitiesAndTasks> responsibilitiesAndTasksQueryWrapper = new QueryWrapper<ResponsibilitiesAndTasks>();
        responsibilitiesAndTasksQueryWrapper.eq("emergency_plan_id", id);
        List<ResponsibilitiesAndTasks> responsibilitiesAndTasksList = responsibilitiesAndTasksMapper.selectList(responsibilitiesAndTasksQueryWrapper);


        String ids_s1 = emergencyPlanManagement.getEmergencyMaterialsIds();
        long[] ids_l1 = Arrays.stream(ids_s1.split(",")).mapToLong(Long::parseLong).toArray();
        List<EmergencyMaterialsInventoryManagement> materialsList = new LinkedList<>();
        for(long materielsId :ids_l1){
            QueryWrapper<EmergencyMaterialsInventoryManagement> emergencyMaterialsInventoryManagementQueryWrapper = new QueryWrapper<EmergencyMaterialsInventoryManagement>();
            emergencyMaterialsInventoryManagementQueryWrapper.eq("id",materielsId);
            List<EmergencyMaterialsInventoryManagement> emergencyMaterialsInventoryManagementList=emergencyMaterialsInventoryManagementMapper.selectList(emergencyMaterialsInventoryManagementQueryWrapper);
            if(emergencyMaterialsInventoryManagementList.size()==0){
                break;
            }
            materialsList.add(emergencyMaterialsInventoryManagementList.get(0));
        }

        EmergencyPlanManagementDTOVO res=new EmergencyPlanManagementDTOVO();
        EmergencyPlanManagementVO vo =new EmergencyPlanManagementVO();
        BeanUtils.copyProperties(emergencyPlanManagement,vo);
        Organization org = organizationMapper.selectById(vo.getOrganizationId());
        vo.setOrganizationName(org==null?"该部门不存在":org.getName());
        String ids_s=vo.getPersonIds();
        long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();
        List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
            SysUser p_org = sysUserMapper.selectById(tmp_id);
            return p_org == null ? "该用户不存在" : p_org.getName();
        }).collect(Collectors.toList());
        vo.setPersonNames(names);
        res.setEmergencyPlanManagementVO(vo);

        List<ResponsibilitiesAndTasksVO> voList=new LinkedList<>();
        for(int i=0;i<responsibilitiesAndTasksList.size();i++){
            ResponsibilitiesAndTasksVO vos=new ResponsibilitiesAndTasksVO();
            BeanUtils.copyProperties(responsibilitiesAndTasksList.get(i),vos);
            SysUser userid =sysUserMapper.selectById(vos.getNameId());
            vos.setPersonnelName(userid==null?"该用户不存在":userid.getName());
            voList.add(vos);
        }
        res.setResponsibilitiesAndTasksVOList(voList);

        List<EmergencyMaterialsInventoryManagementVO> voList1=new LinkedList<>();
            for(int i=0;i<materialsList.size();i++){
                EmergencyMaterialsInventoryManagementVO vos1=new EmergencyMaterialsInventoryManagementVO();
                BeanUtils.copyProperties(materialsList.get(i),vos1);
                SysPosition local= sysPositionMapper.selectById(vos1.getLocaleOrganizationId());
                vos1.setOrganizationLocale(local==null?"该位置不存在":local.getName());
                Organization org1 = organizationMapper.selectById(vos1.getOrganizationId());
                vos1.setOrganizationName(org1==null?"该部门不存在":org.getName());
                SysUser user = sysUserMapper.selectById(vos1.getLiableP());
                vos1.setLiablePersonnel(user == null ? "该用户已被删除" : user.getName());
                voList1.add(vos1);
            }
        res.setEmergencyMaterialsInventoryManagementVOList(voList1);

        return res;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean deleteByIds(Long[] ids) {
        int res = 0;
        int res2 = 0;
        for (int i = 0; i < ids.length; i++) {
            ;
            //mybatis plus的条件删除
            LambdaQueryWrapper<ResponsibilitiesAndTasks> responsibilitiesAndTasksLambdaQueryWrapper = Wrappers.<ResponsibilitiesAndTasks>lambdaQuery();
            responsibilitiesAndTasksLambdaQueryWrapper.eq(ResponsibilitiesAndTasks::getEmergencyPlanId, ids[i]);
            res += responsibilitiesAndTasksMapper.delete(responsibilitiesAndTasksLambdaQueryWrapper);
            res2 += emergencyPlanManagementMapper.deleteById(ids[i]);
            if (res == 0 || res2 == 0) {
                return false;
            }
//            LambdaQueryWrapper<ReviewRecord> reviewRecordLambdaQueryWrapper = Wrappers.<ReviewRecord>lambdaQuery();
//            reviewRecordLambdaQueryWrapper.eq(ReviewRecord::getEmergencyPlanId, ids[i]);
//            reviewRecordMapper.delete(reviewRecordLambdaQueryWrapper);
//            LambdaQueryWrapper<RevisionRecord> revisionRecordLambdaQueryWrapper = Wrappers.<RevisionRecord>lambdaQuery();
//            revisionRecordLambdaQueryWrapper.eq(RevisionRecord::getEmergencyPlanId, ids[i]);
//            revisionRecordMapper.delete(revisionRecordLambdaQueryWrapper);

//            ResponsibilitiesAndTasksExample responsibilitiesAndTasksExample=new ResponsibilitiesAndTasksExample();
//            RevisionRecordExample revisionRecordExample=new RevisionRecordExample();
//            ReviewRecordExample reviewRecordExample=new ReviewRecordExample();
//            responsibilitiesAndTasksExample.createCriteria().andEmergencyPlanIdEqualTo(ids[i]);
//            revisionRecordExample.createCriteria().andEmergencyPlanIdEqualTo(ids[i]);
//            reviewRecordExample.createCriteria().andEmergencyPlanIdEqualTo(ids[i]);
//            responsibilitiesAndTasksMapper.deleteByExample(responsibilitiesAndTasksExample);
//            revisionRecordMapper.deleteByExample(revisionRecordExample);
//            reviewRecordMapper.deleteByExample(reviewRecordExample);

        } return true;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean patchById(EmergencyPlanManagementDTO emergencyPlanManagementDTO) {
        EmergencyPlanManagement emergencyPlanManagement = emergencyPlanManagementDTO.getEmergencyPlanManagement();
        List<ResponsibilitiesAndTasks> list = emergencyPlanManagementDTO.getResponsibilitiesAndTasksList();
        int result = emergencyPlanManagementMapper.updateById(emergencyPlanManagement);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        LambdaQueryWrapper<ResponsibilitiesAndTasks> query=Wrappers.<ResponsibilitiesAndTasks>lambdaQuery();
        query.eq(ResponsibilitiesAndTasks::getEmergencyPlanId,emergencyPlanManagement.getId());
        responsibilitiesAndTasksMapper.delete(query);
        list.forEach(detail -> {
            detail.setEmergencyPlanId(emergencyPlanManagement.getId());
            responsibilitiesAndTasksMapper.insert(detail);
        });
        return true;
    }

    public IPage<EmergencyPlanManagementVO> getListByQO(EmergencyPlanManagementQO emergencyPlanManagementQO) {
        Page<EmergencyPlanManagementVO> page = new Page<>(emergencyPlanManagementQO.getCurrent(), emergencyPlanManagementQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<EmergencyPlanManagementVO> ans = emergencyPlanManagementMapper.getListByQO(page, emergencyPlanManagementQO);
        for (EmergencyPlanManagementVO record : ans.getRecords()) {
            Organization org = organizationMapper.selectById(record.getOrganizationId());
            record.setOrganizationName(org==null?"该部门不存在":org.getName());
            SysUser user = sysUserMapper.selectById(record.getCreaterId());
            record.setCreaterName(org==null?"该创建人不存在":user.getName());
            record.setEmergencyMaterialsIds(record.getEmergencyMaterialsIds()==null?"该物资不存在":record.getEmergencyMaterialsIds());
            String ids_s=record.getPersonIds();
            long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();
            List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
                SysUser p_org = sysUserMapper.selectById(tmp_id);
                return p_org == null ? "该用户不存在" : p_org.getName();
            }).collect(Collectors.toList());
            record.setPersonNames(names);
        }
        return ans;
    }

    public Map<Integer, Integer> type1(Long id, Long companyId) {
        Map<Integer, Integer> ans = new HashMap<>();
        List<EmergencyPlanManagement> list = null;
        if (id == null) {
            LambdaQueryWrapper<EmergencyPlanManagement> query = Wrappers.<EmergencyPlanManagement>lambdaQuery();
            query.eq(EmergencyPlanManagement::getCompanyId, companyId);
            list = emergencyPlanManagementMapper.selectList(query);
        } else {
//            Queue<Long> queue = new LinkedList<>();
//            List<Long> ids = new LinkedList<>();
//            ids.add(id);
//            queue.add(id);
//            while (!queue.isEmpty()) {
//                Long front = queue.poll();
//                LambdaQueryWrapper<Organization> query = Wrappers.<Organization>lambdaQuery();
//                query.eq(Organization::getPid, front);
//                List<Organization> tmp = organizationMapper.selectList(query);
//                for (Organization organization : tmp) {
//                    ids.add(organization.getId());
//                    queue.add(organization.getId());
//                }
//            }
//            LambdaQueryWrapper<EmergencyPlanManagement> query = Wrappers.<EmergencyPlanManagement>lambdaQuery();
//            query.in(EmergencyPlanManagement::getId, ids);
//            list = emergencyPlanManagementMapper.selectList(query);
            LambdaQueryWrapper<EmergencyPlanManagement> query = Wrappers.<EmergencyPlanManagement>lambdaQuery();
            query.eq(EmergencyPlanManagement::getOrganizationId, id);
            list = emergencyPlanManagementMapper.selectList(query);
        }
        if (list == null) {
            return ans;
        } else {
            for (EmergencyPlanManagement emergencyPlanManagement : list) {
                if (!ans.containsKey(emergencyPlanManagement.getTypeId())) {
                    ans.put(emergencyPlanManagement.getTypeId(), 1);
                } else {
                    ans.put(emergencyPlanManagement.getTypeId(), ans.get(emergencyPlanManagement.getTypeId()) + 1);
                }
            }
        }
        return ans;
    }

    public List<RevisionRecordVO> getRevisionRecord(Long id) {
        LambdaQueryWrapper<RevisionRecord> queryWrapper=Wrappers.lambdaQuery();
        queryWrapper.eq(RevisionRecord::getEmergencyPlanId,id);
        List<RevisionRecord> ans=revisionRecordMapper.selectList(queryWrapper);
        List<RevisionRecordVO> revisionRecordVOList=new LinkedList<>();
        for (RevisionRecord an : ans) {
            RevisionRecordVO tmp=new RevisionRecordVO();
            BeanUtils.copyProperties(an,tmp);
            String[] revisonIds=an.getReviserIds().split(",");
            List<String> userList=new LinkedList<>();
            for (String revisonId: revisonIds) {
                SysUser user= sysUserMapper.selectById(Long.parseLong(revisonId));
                userList.add(user.getUsername());
            }
            tmp.setRevisiorNames(userList);
            Long organationId=an.getOrganizationId();
            Organization organization= organizationMapper.selectById(organationId);
            tmp.setDepartmentName(organization.getName());
            revisionRecordVOList.add(tmp);
        }
        return revisionRecordVOList;
    }

    public List<ReviewRecordVO> getReviewRecord(Long id) {
        LambdaQueryWrapper<ReviewRecord> queryWrapper=Wrappers.lambdaQuery();
        queryWrapper.eq(ReviewRecord::getEmergencyPlanId,id);
        List<ReviewRecord> ans=reviewRecordMapper.selectList(queryWrapper);
        List<ReviewRecordVO> reviewRecordVOList=new LinkedList<>();
        for (ReviewRecord an : ans) {
            ReviewRecordVO tmp=new ReviewRecordVO();
            BeanUtils.copyProperties(an,tmp);
            String[] reviewerIds=an.getReviewerIds().split(",");
            List<String> userList=new LinkedList<>();
            for (String reviewerId : reviewerIds) {
                SysUser user= sysUserMapper.selectById(Long.parseLong(reviewerId));
                userList.add(user.getUsername());
            }
            tmp.setReviewerNames(userList);
            Long organationId=an.getOrganizationId();
            Organization organization= organizationMapper.selectById(organationId);
            tmp.setDepartmentName(organization.getName());
            reviewRecordVOList.add(tmp);
        }
        return reviewRecordVOList;
    }
}
